package com.robooot.business_counter.exception;

import com.robooot.business_counter.model.ApiResult;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class ExceptionAdvice {

    private Log log = LogFactory.getLog(getClass());


    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseEntity<?> handleException(Exception e) {
        log.error(e);
        ApiResult result = ApiResult.bad(185, e.getMessage());
        return ResponseEntity.ok(result);
    }

    @ExceptionHandler(BizException.class)
    @ResponseBody
    public ResponseEntity<?> handleBizException(BizException e) {
        log.error(e);
        ApiResult result = ApiResult.bad(e.getErrorCode(), e.getMsg());
        return ResponseEntity.ok(result);
    }


    /**
     * 实现ErrorController 对spring boot 内部的404，500 等异常处理为统一异常
     */
//    @Controller
//    class BootDefaultError implements ErrorController {
//
//        @Override
//        public String getErrorPath() {
//            return "/error";
//        }
//
//        @RequestMapping
//        public ResponseEntity<?> error(HttpServletRequest request) {
//            Integer statusCode = (Integer) request
//                    .getAttribute("javax.servlet.error.status_code");
//            ApiResult result = ApiResult.bad(statusCode, HttpStatus.valueOf(statusCode).getReasonPhrase());
//            return ResponseEntity.ok(result);
//        }
//
//    }
}
